package com.thghh.bcode.compiler;

import javax.tools.SimpleJavaFileObject;
import java.io.IOException;
import java.io.Writer;
import java.net.URI;

/**
 * @author Zhikang.Peng
 * @version 1.0
 * @email thghh@qq.com
 * @date 2020/12/4 16:42
 */
public class StringJavaFileObject extends SimpleJavaFileObject {

    private StringBuilder contents;
    /**
     * Construct a SimpleJavaFileObject of the given className and with the
     * given content.
     *
     * @param className class name
     * @param content java source string
     */
    protected StringJavaFileObject(String className, String content) {
        super(URI.create("memory:///" + className.replaceAll("\\.", "/") + Kind.SOURCE.extension),  Kind.SOURCE);
        this.contents.append(content);
    }

    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
        return contents;
    }

    @Override
    public Writer openWriter() {
        return new Writer() {
            @Override
            public Writer append(CharSequence csq) throws IOException {
                contents.append(csq);
                return this;
            }

            @Override
            public void close() {
            }

            @Override
            public void flush() {
            }

            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {
                contents.append(cbuf, off, len);
            }
        };
    }

}
